package com.djhu.aspect.limit;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author by zw on 2018/5/9.
 */
public class RedisLimiter implements Limit {
    private RedisTemplate redisTemplate;

    @Override
    public synchronized boolean limit(String key, Long timeout, Integer count) {
        if (!redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().set(key,1);
            redisTemplate.expire(key,timeout, TimeUnit.SECONDS);
            return true;
        }else {
            Long size = Long.valueOf( String.valueOf(redisTemplate.opsForValue().get(key)));
            if (size>count){
                return false;
            }
            redisTemplate.opsForValue().increment(key,1);
            return true;
        }
    }
}